package main

import (
	"encoding/json"
	"fmt"
	"github.com/panjf2000/gnet/v2/pkg/logging"
	"go.uber.org/atomic"
	"net"
	"strconv"
	"time"
	"wths/wthsjy-im/plugins/log"
	"wths/wthsjy-im/protocol"
)

var index atomic.Int64

func main() {
	for i := 0; i < 100; i++ {
		go run()
	}

	for {
		time.Sleep(time.Second * 10)
	}
}
func run() {
	conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
		IP: net.IPv4(101, 34, 7, 166),
		//IP:   net.IPv4(127, 0, 0, 1),
		Port: 9000,
	})
	if err != nil {
		logging.Error(err)
		return
	}

	if _, err = conn.Write(getAuthPacketBytes()); err != nil {
		log.Debug("Write").Msg(err)
	}
	_, _ = protocol.ReadIO(conn)

	if _, err = conn.Write(getSubscribePacketBytes()); err != nil {
		log.Debug("Write").Msg(err)
	}
	for {
		packet, err := protocol.ReadIO(conn)
		if err != nil {
			log.Error("ReadIO").Msg(err)
			continue
		}
		log.Debug("recv").Msg(string(packet.Data()), err)
	}

}

var st = time.Now().UnixNano()

func getAuthPacketBytes() []byte {
	p, _ := protocol.NewConnectPacket(fmt.Sprintf("client_%d_%d", st, index.Add(1)), false)
	bs, _ := protocol.Encode(p)
	log.Debug("getAuthPacketBytes").Msg(len(bs))
	return bs
}
func getSubscribePacketBytes() []byte {
	p, _ := protocol.NewSubscribePacket([]string{"topic111"})
	//p, _ := protocol.NewSubscribePacket([]string{fmt.Sprintf("topic_%d", time.Now().UnixNano())})
	bs, _ := protocol.Encode(p)
	log.Debug("getSubscribePacketBytes").Msg(len(bs))
	return bs
}

func getRandPacketBytes() []byte {
	mp := map[string]string{
		"time": time.Now().String(),
		"nano": strconv.FormatInt(time.Now().UnixNano(), 10),
		"txt":  time.Now().String(),
	}

	bs, _ := json.Marshal(mp)
	p, _ := protocol.NewPublishPacket(fmt.Sprintf("topic_%d", time.Now().UnixNano()), bs)
	bs, _ = protocol.Encode(p)
	return bs
}
